package com.up.interview.redis.xianliu;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author: liuchengjun
 * @title: BaseRateLimit
 * @projectName: 海联技术中台V2.0
 * @depart 软件事业部
 * @description:
 * @date: 2025/10/21/周二 15:38 (星期二)
 * @since V2.0
 */
public abstract class BaseRateLimit implements RateLimiter{
    @Autowired
    protected RateLimitConfig rateLimitConfig;

    protected abstract boolean acquire();

    @Override
    public boolean tryAcquire() {
        return acquire();
    }

    @Override
    public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException {
        long deadline = System.currentTimeMillis() + unit.toMillis(timeout);
        while (true) {
            // 尝试获取许可
            if (tryAcquire()) {
                return true;
            }

            // 检查是否超时
            long remainingTime = deadline - System.currentTimeMillis();
            if (remainingTime <= 0) {
                return false; // 超时
            }
            // 每次等待500ms  等待窗口内有请求过期
            Thread.sleep(500);
        }
    }


    @Override
    public RateLimitConfig getConfig() {
        return rateLimitConfig;
    }
}
